package stiletto.user.service.impl;

import org.springframework.dao.DataRetrievalFailureException;
import stiletto.user.dao.UserDao;
import stiletto.user.domain.User;
import stiletto.user.service.UserNotFoundException;
import stiletto.user.service.UserService;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: 82022170
 * Date: 13. 10. 28
 * Time: 오후 4:02
 * To change this template use File | Settings | File Templates.
 */
public class UserServiceImpl implements UserService {
  private UserDao userDao;

  @Override
  public void setUserDao(UserDao newUserDao) {
    userDao = newUserDao;
  }

  public UserDao getUserDao() {
    return userDao;
  }

  @Override
  public void addUser(User newUser) {
    userDao.insert(newUser);
  }

  @Override
  public void updateUser(User user) {
    userDao.update(user);
  }

  @Override
  public synchronized void deactivateUser(String email) {
    User user = userDao.findOneUser(email);
    user.deactivate();
    userDao.update(user);
  }

  @Override
  public synchronized void activateUser(String email) throws UserNotFoundException {
    User user = null;

    try {
      user = userDao.findOneUser(email);
    } catch (DataRetrievalFailureException drfe) {
      throw new UserNotFoundException(drfe);
    }

    user.activate();
    userDao.update(user);
  }

  @Override
  public User findOneUser(String email) throws UserNotFoundException  {
    User user = null;

    try {
      user = userDao.findOneUser(email);
    } catch (DataRetrievalFailureException drfe) {
      throw new UserNotFoundException(drfe);
    }

    return user;
  }

  @Override
  public List<User> findAllUsers() throws UserNotFoundException {
    List<User> found = null;

    try {
      found = userDao.findAllUsers();
    } catch (DataRetrievalFailureException drfe) {
      throw new UserNotFoundException(drfe);
    }

    return found;
  }

  @Override
  public List<User> findUsersByScreenName(String screenName) throws UserNotFoundException {
    List<User> found = null;

    try {
      found = userDao.findUsersByScreenName(screenName);
    } catch (DataRetrievalFailureException drfe) {
      throw new UserNotFoundException(drfe);
    }

    return found;
  }
}